//
//  UIViewController+Utility.m
//  GC_OC
//
//  Created by  Quan He on 2022/4/8.
//

#import "UIViewController+Utility.h"
#import "UIWindow+Utility.h"

@implementation UIViewController (Utility)
+ (UIViewController *)findBestViewController:(UIViewController *)vc
{
    if (vc.presentedViewController) {
        // Return presented view controller
        return [UIViewController findBestViewController:vc.presentedViewController];
        
    } else if ([vc isKindOfClass:[UISplitViewController class]]) {
        // Return right hand side
        UISplitViewController *svc = (UISplitViewController *)vc;
        if (svc.viewControllers.count > 0)
            return [UIViewController findBestViewController:svc.viewControllers.lastObject];
        else
            return vc;
        
    } else if ([vc isKindOfClass:[UINavigationController class]]) {
        // Return top view
        UINavigationController *svc = (UINavigationController *)vc;
        if (svc.viewControllers.count > 0)
            return [UIViewController findBestViewController:svc.topViewController];
        else
            return vc;
        
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        // Return visible view
        UITabBarController *svc = (UITabBarController *)vc;
        if (svc.viewControllers.count > 0)
            return [UIViewController findBestViewController:svc.selectedViewController];
        else
            return vc;
    } else {
        return vc;
    }
}

+ (UIViewController *)currentViewController
{
    UIWindow *keyWindow = [UIWindow availableWindow];
    NSAssert(keyWindow != nil, @"KeyWindow is nil");

    UIViewController *viewController = [keyWindow rootViewController];
    return [UIViewController findBestViewController:viewController];
}

@end
